const { request } = require('../../utils/api');

Page({
  data: {
    title: '',
    content: '',
    location: '',
    weather: '',
    mood: ''
  },

  onTitleInput(e) {
    this.setData({
      title: e.detail.value
    });
  },

  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
  },

  onLocationInput(e) {
    this.setData({
      location: e.detail.value
    });
  },

  onWeatherInput(e) {
    this.setData({
      weather: e.detail.value
    });
  },

  onMoodInput(e) {
    this.setData({
      mood: e.detail.value
    });
  },

  async onSubmit() {
    const { title, content, location, weather, mood } = this.data;
    
    // 获取用户信息
    const user = wx.getStorageSync('userInfo');
    console.log('当前用户信息:', user);

    if (!user || !user.id) {
      console.log('用户未登录或用户信息不完整');
      wx.showToast({ 
        title: '请先登录', 
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 2000);
      return;
    }

    if (!title || !content) {
      wx.showToast({
        title: '标题和内容不能为空',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    try {
      // 构建请求数据
      const requestData = {
        title: title.trim(),
        content: content.trim(),
        location: location ? location.trim() : '',
        weather: weather ? weather.trim() : '',
        mood: mood ? mood.trim() : '',
        date: new Date().toISOString().split('T')[0]  // 添加当前日期
      };

      console.log('提交的数据:', requestData);
      console.log('用户ID类型:', typeof user.id);
      console.log('用户ID值:', user.id);

      const response = await request('/api/diaries', {
        method: 'POST',
        data: requestData
      });

      console.log('发布日记响应:', response);

      if (response.success) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 2000);
      } else {
        throw new Error(response.message || '发布失败');
      }
    } catch (error) {
      console.error('发布失败:', error);
      wx.showToast({
        title: error.message || '发布失败',
        icon: 'none',
        duration: 2000
      });
    }
  }
}); 